import numpy as np # numpy: maths on lists of numbers
import pandas as pd # pandas: tables of data (dataframes)
import matplotlib.pyplot as plt # matplotlib: plots
import seaborn as sns # seaborn: nicer plots, built on matplotlib
from scipy import stats # scipy.stats: statistical tests, such as the t-test
sns.set_theme(style="white") # use a plain white plot style
np.random.seed(42) # make the random numbers the same each time you run the notebookHypothesis Testing
Workshop 6 
This week has four core ideas:
- The standard error: how far a sample mean usually is from the true mean
- Confidence intervals: a range for the true value, from one sample
- The t-test: is a difference between two groups bigger than chance?
- A t-test on every pixel: why most “damaged buildings” are false when damage is rare
We use the same U.S. Current Population Survey (CPS) data as in Workshop 5.
Setup
We load the data and make the same choices as last week: 2013 only, income in $ thousands, and incomes below $200k.
cps = pd.read_csv("https://storage.googleapis.com/qm2/wk7/cps.csv") # load the survey data from the web
df = cps[cps["year"] == 2013].copy() # keep only the 2013 survey
df["income"] = df["incwage"] / 1000 # make a new column: income in $ thousands
df = df[df["income"] < 200] # keep only people who earn less than $200k
unions = df[df["union"] != 0].copy() # keep people who were asked the union question (0 = not asked)
unions["member"] = (unions["union"] == 2).astype(int) # new column: 1 if a union member (code 2), 0 if not
print(len(df), "people") # how many rows (people) are in df
print(len(unions), "people were asked about union membership") # how many rows are in unions52923 people
8697 people were asked about union membership
Columns we use: sex (1 = male, 2 = female), union (0 = not asked, 2 = member), income ($ thousands), occupation.
1. The standard error
The standard error (SE) measures how far a sample mean usually is from the true mean. It gets smaller as the sample gets bigger:
\[SE = \frac{\sigma}{\sqrt{n}}\]
where \(\sigma\) is the standard deviation and \(n\) is the sample size. We check this with the sample_means function from last week.
def sample_means(values, n, reps=10000): # a function: take many samples and return their means
means = [] # an empty list to hold the means
for i in range(reps): # repeat `reps` times
sample = values.sample(n, replace=True) # take a random sample of n people
means.append(sample.mean()) # add the mean of this sample to the list
return np.array(means) # give back the list of means
p = unions["member"].mean() # the true share of union members (mean of 0s and 1s)
print("True union membership rate:", round(p, 3)) # show it, rounded to 3 decimal placesTrue union membership rate: 0.141
sigma = unions["member"].std() # the standard deviation of the whole population
sizes = [10, 30, 100, 300, 1000, 3000] # the sample sizes we will try
theory_se = [] # an empty list for the standard errors from the formula
simulated_se = [] # an empty list for the standard errors from simulation
for n in sizes: # for each sample size...
theory_se.append(sigma / np.sqrt(n)) # ...use the formula sigma / sqrt(n)
means = sample_means(unions["member"], n, reps=2000) # ...take 2,000 samples of size n
simulated_se.append(means.std()) # ...and measure how much their means spread out
plt.plot(sizes, theory_se, color="black", label="Theory: sigma / sqrt(n)") # draw the formula as a line
plt.plot(sizes, simulated_se, "o", color="red", label="Simulation") # draw the simulation as dots
plt.xscale("log") # use a log scale on the x-axis
plt.xlabel("Sample size n (log scale)") # label the x-axis
plt.ylabel("Standard error") # label the y-axis
plt.title("Uncertainty shrinks as the sample gets bigger") # add a title
plt.legend() # show the labels of the line and the dots
plt.show() # draw the plot
2. Confidence intervals
In real life we have one sample. A 95% confidence interval is
\[\bar{x} \pm 1.96 \times SE, \qquad SE = \frac{s}{\sqrt{n}}\]
where \(\bar{x}\) is the sample mean and \(s\) is the sample standard deviation.
sample = df.sample(1000) # take a random sample of 1,000 people
mean = sample["income"].mean() # the sample mean
s = sample["income"].std() # the sample standard deviation
n = len(sample) # the sample size
se = s / np.sqrt(n) # the standard error
lower = mean - 1.96 * se # the low end of the 95% confidence interval
upper = mean + 1.96 * se # the high end of the 95% confidence interval
print("Sample mean:", round(mean, 2)) # show the sample mean
print("Standard error:", round(se, 2)) # show the standard error
print("95% CI:", round(lower, 2), "to", round(upper, 2)) # show the confidence interval
print("Population mean:", round(df["income"].mean(), 2)) # the true mean, to compareSample mean: 45.66
Standard error: 0.99
95% CI: 43.71 to 47.6
Population mean: 46.75
What does “95%” mean?
The true mean is a fixed number. The 95% describes the method: if we repeat the study many times, 95% of the intervals contain the true mean. Let’s check with 100 samples.
z = 1.96 # the multiplier: 1.96 gives a 95% interval
n = 1000 # the sample size of each study
true_mean = df["income"].mean() # the true mean income
misses = 0 # a counter for intervals that miss the true mean
for i in range(100): # repeat the study 100 times
x = df["income"].sample(n) # take a new random sample
margin = z * x.std() / np.sqrt(n) # the margin of error: z times the standard error
lower = x.mean() - margin # the low end of the interval
upper = x.mean() + margin # the high end of the interval
if lower <= true_mean <= upper: # if the interval contains the true mean...
colour = "steelblue" # ...draw it in blue
else: # if it misses...
colour = "red" # ...draw it in red
misses = misses + 1 # ...and add 1 to the counter
plt.plot([lower, upper], [i, i], color=colour) # draw the interval as a horizontal line
plt.axvline(true_mean, color="black", linestyle="--") # a dashed line at the true mean
plt.xlabel("Income ($ thousands)") # label the x-axis
plt.ylabel("Study number") # label the y-axis
plt.title(str(misses) + " of 100 intervals miss the true mean (red)") # the title shows the number of misses
plt.show() # draw the plot
3. The t-test: is there a gender pay gap?
In our sample, men earn more than women on average. But two random groups never have exactly the same mean. A t-test asks: is the difference bigger than chance can explain? Four steps:
1. State the hypotheses. \(H_0\): no difference in mean income between men and women. \(H_a\): there is a difference.
2. Choose a significance level. \(\alpha = 0.05\) gives a critical value of 1.96; \(\alpha = 0.01\) gives 2.58. If \(t\) is further from zero than the critical value, we reject \(H_0\).
But even if there were no difference in the population, two random groups would never have exactly the same mean: that’s sampling error. A hypothesis test asks whether the difference is bigger than sampling error can plausibly explain. Four steps:
1. State the hypotheses
- \(H_0\): there is no difference in mean income between men and women (\(\mu_{men} = \mu_{women}\))
- \(H_a\): there is a difference (\(\mu_{men} \neq \mu_{women}\))
2. Select an \(\alpha\) level and critical value
With large samples the t distribution is essentially normal, so: * \(\alpha = 0.05\) (95% confidence): critical value 1.96 * \(\alpha = 0.01\) (99% confidence): critical value 2.58
If the test statistic is further from zero than the critical value, we reject \(H_0\).
def plot_z(t): # a function: show where t falls on the normal curve
x = np.linspace(-8, 8, 400) # 400 points from -8 to 8
plt.plot(x, stats.norm.pdf(x), color="black") # draw the normal curve
plt.axvline(-1.96, color="blue", linestyle="--", label="±1.96 (95%)") # the 95% critical value, left
plt.axvline(1.96, color="blue", linestyle="--") # the 95% critical value, right
plt.axvline(-2.58, color="green", linestyle="--", label="±2.58 (99%)") # the 99% critical value, left
plt.axvline(2.58, color="green", linestyle="--") # the 99% critical value, right
plt.axvline(t, color="red", linewidth=2, label="t = " + str(round(t, 2))) # our test statistic, in red
plt.title("Where does the test statistic fall?") # add a title
plt.legend() # show the labels
plt.show() # draw the plot3. Compute the test statistic. \(t\) is the signal (the difference in means) divided by the noise (the standard error of the difference):
\[t = \frac{\bar{x}_1-\bar{x}_2}{\sqrt{\frac{s^2_1}{n_1} + \frac{s^2_2}{n_2}}}\]
def manual_ttest(group1, group2): # a function: the Welch t statistic, by hand
signal = group1.mean() - group2.mean() # the signal: the difference between the two means
noise = np.sqrt(group1.var() / len(group1) + group2.var() / len(group2)) # the noise: the SE of the difference
t = signal / noise # the t statistic: signal divided by noise
print("Group 1:", len(group1), "people, mean", round(group1.mean(), 2)) # show group 1
print("Group 2:", len(group2), "people, mean", round(group2.mean(), 2)) # show group 2
print("Difference:", round(signal, 2), " SE of the difference:", round(noise, 2), " t:", round(t, 2)) # show the result
return t # give back t
men = sample[sample["sex"] == 1]["income"] # incomes of the men in the sample (sex 1)
women = sample[sample["sex"] == 2]["income"] # incomes of the women in the sample (sex 2)
t = manual_ttest(men, women) # run the t-test: men are group 1, women are group 2Group 1: 467 people, mean 52.8
Group 2: 533 people, mean 39.4
Difference: 13.41 SE of the difference: 1.98 t: 6.79
4. Make a decision.
plot_z(t) # show where our t falls
The scipy library gives the same \(t\), and also a p-value: the probability of a difference this big if \(H_0\) is true.
result = stats.ttest_ind(men, women, equal_var=False) # the same test with scipy (equal_var=False means Welch)
print("t =", round(result.statistic, 2)) # the t statistic: the same as ours
print("p-value =", result.pvalue) # the p-valuet = 6.79
p-value = 2.127970730519472e-11
Exercise
- Write two sentences that explain the result of this test. What does the p-value mean, and what does it not mean?
- Do union members earn more than non-members? Use all of
unionsandmanual_ttest().
# your code here4. A t-test on every pixel: why most “damaged buildings” are false
The lecture’s damage detector (PWTT) runs one t-test per pixel: did the radar signal change after the attack? A city has thousands of buildings, so it runs thousands of tests.
Below is a toy city of 10,000 buildings. Only 1% are damaged, and the test is very accurate. Run the cell, then change the numbers at the top and run it again.
# ---- Change these and run the cell again ----
share_damaged = 0.01 # the prior: the share of buildings that are damaged
drop_db = 3 # how much damage lowers the radar signal (bigger = easier to see)
alpha = 0.05 # flag a building if its p-value is below alpha
# ----------------------------------------------
rows = [] # an empty list: one entry per building
for row in range(100): # the city is a grid of 100 rows...
for col in range(100): # ...and 100 columns: 10,000 buildings
damaged = np.random.random() < share_damaged # True for about 1% of buildings
before = np.random.normal(0, 1, 12) # 12 noisy radar images before the strikes
after = np.random.normal(0, 1, 4) # 4 noisy radar images after the strikes
if damaged: # if this building is damaged...
after = after - drop_db # ...its radar signal drops after the strikes
p_value = stats.ttest_ind(after, before, equal_var=False).pvalue # one t-test for this building
rows.append({"row": row, "col": col, "damaged": damaged, "flagged": p_value < alpha}) # save the result
city = pd.DataFrame(rows) # turn the list into a table
real = city[(city["damaged"] == True) & (city["flagged"] == True)] # damaged and flagged: real damage found
false = city[(city["damaged"] == False) & (city["flagged"] == True)] # intact but flagged: false alarms
print("Damaged buildings found:", len(real)) # how many of them the test found
print("False alarms:", len(false)) # how many intact buildings were flagged
print("Share of flags that are real:", round(len(real) / (len(real) + len(false)), 2)) # real flags / all flags
plt.scatter(false["col"], false["row"], color="orange", s=8, label="False alarm") # false alarms in orange
plt.scatter(real["col"], real["row"], color="red", s=8, label="Real damage found") # real damage in red
plt.title("What the t-test flags") # add a title
plt.legend(loc="upper right") # show the labels
plt.show() # draw the plotDamaged buildings found: 104
False alarms: 584
Share of flags that are real: 0.15

Why? With 9,900 intact buildings, a 5% false-alarm rate gives about 500 false flags. With 100 damaged buildings, there can be at most 100 real flags. This is Bayes’ theorem:
\[P(\text{damaged} \mid \text{flagged}) = \frac{P(\text{flagged} \mid \text{damaged})\,P(\text{damaged})}{P(\text{flagged} \mid \text{damaged})\,P(\text{damaged}) + P(\text{flagged} \mid \text{intact})\,P(\text{intact})}\]
The prior \(P(\text{damaged})\) is small, so the false alarms (the second part of the bottom line) are most of the flags.
Iran
In 30 test cities, the PWTT found 71% of damaged buildings and flagged 16% of intact ones (Ballinger 2025, Remote Sensing of Environment). In Iran nobody knows the prior, so choose your own guess.
# ---- Change this and run the cell again ----
iran_prior = 0.01 # your guess: the share of buildings damaged in the area you map
# --------------------------------------------
buildings = 10000 # imagine an area with 10,000 buildings
damaged = iran_prior * buildings # the number of damaged buildings
intact = buildings - damaged # the number of intact buildings
pwtt_real = 0.71 * damaged # the PWTT finds 71% of damaged buildings
pwtt_false = 0.16 * intact # the PWTT flags 16% of intact buildings (false alarms)
best_real = 0.99 * damaged # a near-perfect detector finds 99% of damaged buildings
best_false = 0.01 * intact # and flags only 1% of intact buildings
print("PWTT: share of flags that are real:", round(pwtt_real / (pwtt_real + pwtt_false), 2)) # real / all flags
print("Near-perfect: share of flags that are real:", round(best_real / (best_real + best_false), 2)) # real / all flags
detectors = ["PWTT", "Near-perfect"] # the names of the two bars
plt.bar(detectors, [pwtt_real, best_real], color="red", label="Real damage") # the red part of each bar
plt.bar(detectors, [pwtt_false, best_false], bottom=[pwtt_real, best_real], color="orange", label="False alarm") # orange on top
plt.ylabel("Flagged buildings (out of 10,000)") # label the y-axis
plt.title("Iran, if " + str(iran_prior * 100) + "% of buildings are damaged") # the title shows your prior
plt.legend() # show the labels
plt.show() # draw the plotPWTT: share of flags that are real: 0.04
Near-perfect: share of flags that are real: 0.5

Exercise
- In the toy city, set
drop_db = 6(damage that is very easy to see). Are most flags real now? Then setshare_damaged = 0.3. Which change matters more? - Change
iran_prioruntil half of the PWTT bar is red. Is that prior likely for a few targeted strikes?
# your code hereAssessed Question
The URL below contains the 2013 CPS respondents: one row per person, with the same columns as the cps dataframe we used above.
https://oballinger.github.io/BASC0005/data/assessed/w06_cps_2013.csv
Note that the file may have been corrupted; some values or labels may be wrong, so make sure to sense-check your data before answering.
QUESTION: Using df as in the workshop (2013, income < $200k), take everyone in the occupation “Protective Service adj_occupations”. Use the workshop’s manual_ttest() (Welch) to test the gender pay gap in income, with men as group 1 and women as group 2. What is the t-statistic? (2 d.p.)
# your code hereRecap
- The standard error \(\sigma/\sqrt{n}\) shows how far a sample mean usually is from the true mean.
- A 95% confidence interval is \(\bar{x} \pm 1.96\,SE\). The method contains the true value in 95% of samples.
- A t-test divides the difference in means (signal) by its standard error (noise).
- When damage is rare, most flags are false, even from an accurate test. The share of real flags depends on the prior.